// 网络监控仪表盘 JavaScript 主程序

// 格式化工具函数
function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatSpeed(mbps) {
    return mbps.toFixed(2) + ' Mbps';
}

function getSpeedClass(speed) {
    if (speed > 100) return 'speed-high';
    if (speed > 10) return 'speed-medium';
    return 'speed-low';
}

// 更新汇总卡片数据
function updateSummaryCards(summary) {
    document.getElementById('total-interfaces').textContent = summary.total_interfaces || 0;
    document.getElementById('physical-interfaces').textContent = summary.physical_interfaces || 0;
    document.getElementById('virtual-interfaces').textContent = summary.virtual_interfaces || 0;
    document.getElementById('active-interfaces').textContent = summary.active_interfaces || 0;
    document.getElementById('update-time').textContent = summary.update_time;
    
    // 更新运行时间
    if (summary.runtime) {
        updateUptime(summary.runtime);
    }
}

// 更新系统资源卡片数据
function updateSystemCards(system) {
    document.getElementById('cpu-usage').textContent = system.cpu_usage.toFixed(1);
    document.getElementById('memory-usage').textContent = system.memory_usage.toFixed(1);
    document.getElementById('memory-used').textContent = (system.memory_used / 1024 / 1024).toFixed(0);
    document.getElementById('goroutines').textContent = system.goroutines;
    
    // 实时更新更新时间和运行时间
    if (system.update_time) {
        document.getElementById('update-time').textContent = system.update_time;
    }
    if (system.runtime) {
        updateUptime(system.runtime);
    }
}





// 全局变量管理
let interfaceMap = new Map(); // 网卡ID到数据的映射
let interfaceList = []; // 网卡列表
let showVirtualInterfaces = true;
let showIdleInterfaces = true;
let interfaceSearchQuery = ''; // 网卡搜索关键词

// 获取网卡列表
async function fetchInterfaceList() {
    try {
        const response = await fetch('/api/interfaces');
        const data = await response.json();
        interfaceList = data.interfaces || [];
        
        // 更新卡片统计信息
        if (data.summary) {
            document.getElementById('total-interfaces').textContent = data.summary.total_interfaces || 0;
            document.getElementById('physical-interfaces').textContent = data.summary.physical_interfaces || 0;
            document.getElementById('virtual-interfaces').textContent = data.summary.virtual_interfaces || 0;
            document.getElementById('active-interfaces').textContent = data.summary.active_interfaces || 0;
            document.getElementById('update-time').textContent = data.summary.update_time || '加载中...';
        }
        
        // 初始化网卡映射
        interfaceList.forEach(iface => {
            interfaceMap.set(iface.id, {
                id: iface.id,
                name: iface.name,
                type: iface.type,
                isVirtual: iface.isVirtual,
                status: iface.status,
                received_mbps: 0,
                sent_mbps: 0,
                total_received_gb: 0,
                total_sent_gb: 0,
                dropped: 0,
                packets: 0
            });
        });
        
        console.log('网卡列表已加载:', interfaceList.length, '个网卡');
        renderInterfacesTable();
    } catch (error) {
        console.error('获取网卡列表失败:', error);
    }
}

// 根据网卡ID更新数据
function updateInterfaceByID(interfaceId, data) {
    if (interfaceMap.has(interfaceId)) {
        const existing = interfaceMap.get(interfaceId);
        Object.assign(existing, data);
    }
}

// 渲染网卡表格
function renderInterfacesTable() {
    const tbody = document.getElementById('interfaces-tbody');
    const showVirtualCheckbox = document.getElementById('show-virtual');
    const showIdleCheckbox = document.getElementById('show-idle');
    const searchInput = document.getElementById('interface-search');
    const searchResultsInfo = document.getElementById('search-results-info');
    const searchResultsText = document.getElementById('search-results-text');
    const clearSearchBtn = document.getElementById('clear-search');
    
    if (showVirtualCheckbox) {
        showVirtualInterfaces = showVirtualCheckbox.checked;
    }
    
    if (showIdleCheckbox) {
        showIdleInterfaces = showIdleCheckbox.checked;
    }
    
    if (searchInput) {
        interfaceSearchQuery = searchInput.value.toLowerCase().trim();
    }
    
    // 控制清除按钮的显示/隐藏
    if (clearSearchBtn) {
        clearSearchBtn.style.display = interfaceSearchQuery ? 'block' : 'none';
    }
    
    // 过滤网卡
    const allInterfaces = Array.from(interfaceMap.values());
    let filteredInterfaces = allInterfaces.filter(iface => {
        const showVirtual = showVirtualInterfaces || !iface.isVirtual;
        const isIdle = (iface.received_mbps || 0) === 0 && (iface.sent_mbps || 0) === 0;
        const showIdle = showIdleInterfaces || !isIdle;
        
        // 网卡名称搜索过滤
        const matchesSearch = !interfaceSearchQuery || 
            (iface.name && iface.name.toLowerCase().includes(interfaceSearchQuery));
        
        return showVirtual && showIdle && matchesSearch;
    });
    
    // 应用排序
    if (window.networkSorter) {
        filteredInterfaces = window.networkSorter.sortInterfaces(filteredInterfaces);
    }
    
    // 更新搜索结果提示
    if (searchResultsInfo && searchResultsText) {
        if (interfaceSearchQuery) {
            const totalBeforeSearch = allInterfaces.filter(iface => {
                const showVirtual = showVirtualInterfaces || !iface.isVirtual;
                const isIdle = (iface.received_mbps || 0) === 0 && (iface.sent_mbps || 0) === 0;
                const showIdle = showIdleInterfaces || !isIdle;
                return showVirtual && showIdle;
            }).length;
            
            searchResultsText.innerHTML = `搜索 "<span class="search-highlight">${interfaceSearchQuery}</span>": 找到 ${filteredInterfaces.length}/${totalBeforeSearch} 个网卡`;
            searchResultsInfo.classList.remove('hidden');
        } else {
            searchResultsInfo.classList.add('hidden');
        }
    }
    
    if (filteredInterfaces.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" class="loading">暂无网卡数据</td></tr>';
        return;
    }

    // 计算实时汇总数据（仅用于表格总计行）
    let totalDownloadSpeed = 0;
    let totalUploadSpeed = 0;
    let totalDownloadGB = 0;
    let totalUploadGB = 0;
    let totalDropped = 0;
    let activeCount = 0;

    filteredInterfaces.forEach(iface => {
        totalDownloadSpeed += iface.received_mbps || 0;
        totalUploadSpeed += iface.sent_mbps || 0;
        totalDownloadGB += iface.total_received_gb || 0;
        totalUploadGB += iface.total_sent_gb || 0;
        totalDropped += iface.dropped || 0;
        
        if (iface.received_mbps > 0 || iface.sent_mbps > 0) {
            activeCount++;
        }
    });

    let html = '';
    
    // 添加总数据行
    html += `
        <tr class="total-row">
            <td><strong>总计</strong></td>
            <td>
                <span class="interface-type total">
                    📊 总数
                </span>
            </td>
            <td>
                <span class="speed-indicator ${getSpeedClass(totalDownloadSpeed)}">
                    ${formatSpeed(totalDownloadSpeed)}
                </span>
            </td>
            <td>
                <span class="speed-indicator ${getSpeedClass(totalUploadSpeed)}">
                    ${formatSpeed(totalUploadSpeed)}
                </span>
            </td>
            <td>${totalDownloadGB.toFixed(2)} GB</td>
            <td>${totalUploadGB.toFixed(2)} GB</td>
            <td>${totalDropped}</td>
            <td>0.00%</td>
            <td>
                <span class="speed-indicator ${activeCount > 0 ? 'speed-high' : 'speed-low'}">
                    ${activeCount} 活跃
                </span>
            </td>
        </tr>
    `;

    // 添加各个网卡数据
    filteredInterfaces.forEach(iface => {
        const downloadSpeed = iface.received_mbps || 0;
        const uploadSpeed = iface.sent_mbps || 0;
        const totalDownload = iface.total_received_gb || 0;
        const totalUpload = iface.total_sent_gb || 0;
        const dropped = iface.dropped || 0;
        
        // 高亮搜索关键词
        let displayName = iface.name;
        if (interfaceSearchQuery && iface.name.toLowerCase().includes(interfaceSearchQuery)) {
            const regex = new RegExp(`(${interfaceSearchQuery})`, 'gi');
            displayName = iface.name.replace(regex, '<span class="search-highlight">$1</span>');
        }

        html += `
            <tr data-interface-id="${iface.id}" ${iface.isVirtual ? 'class="virtual-interface"' : ''}>
                <td><strong>${displayName}</strong></td>
                <td>
                    <span class="interface-type ${iface.isVirtual ? 'virtual' : 'physical'}">
                        ${iface.isVirtual ? '🌐 虚拟' : '💻 物理'}
                    </span>
                </td>
                <td>
                    <span class="speed-indicator ${getSpeedClass(downloadSpeed)}">
                        ${formatSpeed(downloadSpeed)}
                    </span>
                </td>
                <td>
                    <span class="speed-indicator ${getSpeedClass(uploadSpeed)}">
                        ${formatSpeed(uploadSpeed)}
                    </span>
                </td>
                <td>${totalDownload.toFixed(2)} GB</td>
                <td>${totalUpload.toFixed(2)} GB</td>
                <td>${dropped}</td>
                <td>0.00%</td>
                <td>
                    <span class="speed-indicator ${downloadSpeed > 0 || uploadSpeed > 0 ? 'speed-high' : 'speed-low'}">
                        ${downloadSpeed > 0 || uploadSpeed > 0 ? '活跃' : '空闲'}
                    </span>
                </td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
}

// 初始化SSE连接
function initializeSSE() {
    const eventSource = new EventSource('/api/sse');
    
    eventSource.onopen = function() {
        console.log('SSE连接已建立');
    };

    eventSource.onmessage = function(event) {
        try {
            const data = JSON.parse(event.data);
            if (data.type === 'connected') {
                console.log(data.message);
                return;
            }
        } catch (e) {
            // 忽略连接消息
        }
    };

    eventSource.addEventListener('data', function(event) {
        try {
            const data = JSON.parse(event.data);

            if (data.interfaces) {
                // 定向更新网卡数据
                Object.keys(data.interfaces).forEach(name => {
                    const interfaceData = data.interfaces[name];
                    if (interfaceData.id) {
                        updateInterfaceByID(interfaceData.id, interfaceData);
                    }
                });
                renderInterfacesTable();
            }

            // 卡片统计信息只从/api/interfaces接口获取，不更新SSE的summary数据

            if (data.system) {
                updateSystemCards(data.system);
            }
        } catch (error) {
            console.error('解析数据失败:', error);
        }
    });

    eventSource.addEventListener('error', function(event) {
        console.error('SSE错误:', event.data);
        document.getElementById('interfaces-tbody').innerHTML = 
            '<tr><td colspan="9" class="error">连接中断，正在重连...</td></tr>';
    });

    eventSource.onerror = function() {
        console.error('SSE连接断开');
        // 5秒后自动重连
        setTimeout(() => {
            console.log('尝试重新连接...');
            initializeSSE();
        }, 5000);
    };
}

// 更新运行时间显示
function updateUptime(runtime) {
    const uptimeElement = document.getElementById('uptime');
    if (uptimeElement && runtime) {
        uptimeElement.textContent = runtime;
    }
}

// 获取后端版本信息
function fetchVersion() {
    fetch('/api/version')
        .then(response => response.json())
        .then(data => {
            const versionElements = document.querySelectorAll('.version-display');
            versionElements.forEach(element => {
                if (element) {
                    element.textContent = data.version || '1.2.2';
                }
            });
            
            const appNameElements = document.querySelectorAll('.app-name-display');
            appNameElements.forEach(element => {
                if (element) {
                    element.textContent = data.app_name || 'Go网络监控';
                }
            });
        })
        .catch(error => {
            console.error('获取版本信息失败:', error);
            // 如果获取失败，使用默认值
            const versionElements = document.querySelectorAll('.version-display');
            versionElements.forEach(element => {
                if (element) {
                    element.textContent = '1.2.2';
                }
            });
        });
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeApp);
} else {
    initializeApp();
}

function initializeApp() {
    fetchInterfaceList();
    initializeSSE();
    fetchVersion();
    
    // 添加虚拟网卡显示开关事件监听
    const showVirtualCheckbox = document.getElementById('show-virtual');
    if (showVirtualCheckbox) {
        showVirtualCheckbox.addEventListener('change', function() {
            showVirtualInterfaces = this.checked;
            renderInterfacesTable();
        });
    }
    
    // 添加空闲网卡显示开关事件监听
    const showIdleCheckbox = document.getElementById('show-idle');
    if (showIdleCheckbox) {
        showIdleCheckbox.addEventListener('change', function() {
            showIdleInterfaces = this.checked;
            renderInterfacesTable();
        });
    }
    
    // 添加网卡搜索输入框事件监听
    const searchInput = document.getElementById('interface-search');
    if (searchInput) {
        // 实时搜索（输入时触发）
        searchInput.addEventListener('input', function() {
            interfaceSearchQuery = this.value.toLowerCase().trim();
            renderInterfacesTable();
        });
        
        // 回车键搜索
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                interfaceSearchQuery = this.value.toLowerCase().trim();
                renderInterfacesTable();
            }
        });
    }
    
    // 添加清除搜索按钮事件监听
    const clearSearchBtn = document.getElementById('clear-search');
    if (clearSearchBtn) {
        clearSearchBtn.addEventListener('click', function() {
            const searchInput = document.getElementById('interface-search');
            if (searchInput) {
                searchInput.value = '';
                interfaceSearchQuery = '';
                renderInterfacesTable();
                searchInput.focus(); // 焦点返回到搜索框
            }
        });
    }
    
    // 初始化网卡排序器的表头事件监听器
    setTimeout(() => {
        if (window.networkSorter) {
            window.networkSorter.setupHeaderEventListeners();
        }
    }, 500);
}